<template>
  <div class="employees-container">
    <div class="app-container">
      <page-tools>
        <template #left>
          <span>总记录数: {{ total }} 条</span>
        </template>
        <template #right>
          <el-button v-allow="'import_excel'" type="warning" size="small" @click="$router.push('/import')">excel导入</el-button>
          <el-button v-allow="'export_excel'" type="danger" size="small" @click="handleDownload">excel导出</el-button>
          <el-button v-allow="'add'" type="primary" size="small" @click="showDialog=true">新增员工</el-button>
        </template>
      </page-tools>

      <el-card style="margin-top: 10px;">
        <el-table border :data="data" :default-sort="{prop:'timeOfEntry',order:'ascending'}">
          <el-table-column label="序号" type="index" />
          <el-table-column label="姓名" prop="username" />
          <el-table-column label="图片">
            <template #default="{row}">
              <img :src="row.staffPhoto" alt="" style="width:100%">
            </template>
          </el-table-column>
          <el-table-column label="工号" prop="workNumber" />
          <el-table-column label="聘用形式" prop="formOfEmployment">
            <template #default="{row}">
              {{ EnumerationFormat(row.formOfEmployment) }}
            </template>
          </el-table-column>
          <el-table-column label="部门" prop="departmentName" />
          <el-table-column label="入职时间" prop="timeOfEntry" />
          <el-table-column label="操作" width="280">
            <template #default="{row}">
              <el-button type="text" size="small" @click="$router.push(`/employees/detail?id=${row.id}`)">查看</el-button>
              <el-button type="text" size="small" @click="assignRoles(row.id)">分配角色</el-button>
              <el-button v-allow="'delete'" type="text" size="small" @click="hDel(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row type="flex" justify="center" align="middle" style="height: 60px">
          <el-pagination
            :current-page="page"
            :page-size="size"
            layout=" prev, pager, next"
            :total="total"
            @current-change="handleCurrentChange"
          />
        </el-row>
      </el-card>
      <!-- 新增  -->
      <el-dialog title="新增编辑" :visible.sync="showDialog" :close-on-click-modal="false">
        <addorEdit @close="hCancel" />
      </el-dialog>
      <!-- 角色管理 -->
      <el-dialog
        title="角色管理"
        :visible.sync="showDialogRole"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
      >
        <assignRole v-if="showDialogRole" :id="cruId" @close="showDialogRole=false" />
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { getEmployessList, delEmployess } from '@/api/employess'
import addorEdit from './employessDialog.vue'
import Enumeration from '@/constant/employees'
import assignRole from './assignRole.vue'
// debugger
const hireType = Enumeration.hireType.reduce((prev, item) => {
  prev[item.id] = item.value
  return prev
}, {})

// console.log(hireType)
export default {
  name: 'Employees',
  components: { addorEdit, assignRole },
  data() {
    return {
      showDialogRole: false,
      showDialog: false,
      data: [], // 员工列表
      page: 1,
      size: 5,
      total: 0,
      cruId: ''
    }
  },
  created() {
    this.loadEmployessList()
  },
  methods: {
    assignRoles(id) {
      this.cruId = id
      this.showDialogRole = true
    },
    // 英文转中文
    formatData(list) {
      const map = {
        'id': '编号',
        'password': '密码',
        'mobile': '手机号',
        'username': '姓名',
        'timeOfEntry': '入职日期',
        'formOfEmployment': '聘用形式',
        'correctionTime': '转正日期',
        'workNumber': '工号',
        'departmentName': '部门',
        'staffPhoto': '头像地址'
      }

      const one = list[0]

      if (!one) return

      const hreads = Object.keys(one).map(item => {
        return map[item]
      })
      // console.log(hread,'hreadddddddddddddddd')
      // debugger
      const data = list.map(item => {
        const key = item['formOfEmployment']
        item['formOfEmployment'] = hireType[key] || '未知'
        return Object.values(item)
      })
      // console.log(data,'dataaaaaaaaaaaaaaaaaaaaa');
      return { hreads, data }
    },
    // 导出
    async handleDownload() {
      try {
        const res = await getEmployessList(this.page, this.size)
        // console.log('getEmployessList', res)
        const { hreads, data } = this.formatData(res.data.rows)

        import('@/vendor/Export2Excel').then(excel => {
        // const tHeader = ['Id', 'Title', 'Author', 'Readings', 'Date']
        // const filterVal = ['id', 'title', 'author', 'pageviews', 'display_time']
        // const list = this.list
        // const data = this.formatJson(filterVal, list)
          excel.export_json_to_excel({
            header: hreads,
            data: data,
            filename: this.filename,
            autoWidth: this.autoWidth,
            bookType: this.bookType
          })
        })
        // 保存数据
      } catch (err) {
        console.log('getEmployessList', err)
      }
    },

    // 删除员工
    hDel(id) {
      this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        await delEmployess(id)
        if (this.data.length === 1) this.page--
        this.loadEmployessList()
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // 枚举
    EnumerationFormat(id) {
      // console.log(id, 'id')
      return hireType[id] || '未知'
    },
    async loadEmployessList() {
      try {
        const res = await getEmployessList(this.page, this.size)
        // console.log('getEmployessList', res)
        this.data = res.data.rows
        this.total = res.data.total
        // 保存数据
      } catch (err) {
        console.log('getEmployessList', err)
      }
    },
    // 分页器
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`)
      this.page = val
      this.loadEmployessList()
    },
    // 关闭对话框
    hCancel(id) {
      console.log(id)
      if (id === '1') {
        this.total++
        this.page = Math.ceil(this.total / this.size)
        this.loadEmployessList()
      }
      console.log(this.page, '----------------')
      this.showDialog = false
    }
  }
}
</script>
